extends RichTextLabel

signal play_ended

onready var timer = $Timer
onready var jixu = $JixuLabel

var ptext = "" setget set_ptext
var pinyin = "" setget set_pinyin
var index = -1
var indexl = -1

var text_list = []
var pinyin_list = []
var slist = []

var pre_text = ""

var play_min_speed = 0.05
var play_max_speed = 0.1


func set_ptext(s: String) -> void:
	index = -1
	text_list = s.split('|')
	
	ptext = s

func set_pinyin(s: String) -> void:
	index = -1
	pinyin_list = s.split('|')
	
	pinyin = s

func next() -> bool:
	index += 1
	
	if index >= len(text_list) or index >= len(pinyin_list):
		return false
		
	pre_text = text
	
	var yin: String = pinyin_list[index]
	var ci: String = text_list[index]
	
	var list = []
	var tmps = ""
	
	var n: int = 0
	for i in yin:
		n += 1
		tmps += i
		list.append(tmps + ("▏" if n%2==0 else ""))
	list.append(ci)
	
	slist = list
	indexl = -1
	
	return true
	
func nextl() -> bool:
	indexl += 1
	if indexl >= len(slist):
		var b = next()
		if b: nextl()
		return b
	
	text = pre_text + slist[indexl]
	
	return true
	

	
func play(min_speed = 0.05, max_speed = 0.1):
	play_min_speed = min_speed
	play_max_speed = max_speed
	
	while true:
		if Input.is_action_pressed("jump")\
		 or Input.is_action_pressed("cursor_shoot"):
			timer.start(rand_range(0.001, 0.002))
		else:
			timer.start(rand_range(play_min_speed, play_max_speed))
		yield(timer, "timeout")
		var prepre_text = pre_text
		if not nextl(): break
		
		if text.ends_with("...")\
		 or text.ends_with("。")\
		 or text.ends_with("！")\
		 or text.ends_with("？"):
			nextl()
			jixu.visible = true
			break
		
func _input(event: InputEvent) -> void:
	if event is InputEventMouseButton or event is InputEventKey:
		if event.is_pressed() and not event.is_echo():
			if jixu.visible == true:
				jixu.visible = false
				
				if index+1 >= len(text_list) or index+1 >= len(pinyin_list):
					emit_signal("play_ended")
				else:
					pre_text = ""
					text = ""
					
				play(play_min_speed, play_max_speed)

func _ready() -> void:
	text = ""
